//file system operation functions (e.g. file, directory operations)
//
#include "stdafx.h"
#include ".\diskio.h"
#include "i18n.h"

CDiskIO::CDiskIO(void)
{
}

CDiskIO::~CDiskIO(void)
{
}

//check whether a file or a directory exists
BOOL CDiskIO::PathExists(LPCTSTR  lpszPath)
{
	return PathFileExists(lpszPath);
}

TCHAR* CDiskIO::FileReadBuffer(LPCTSTR lpszFilename)
{
	CFile f;
	if(f.Open(lpszFilename, CFile::modeRead|CFile::shareDenyNone) == FALSE)
	{
		return NULL;
	}

	DWORD len = (DWORD) f.GetLength();
	if (len<=0) 	return NULL;
	BYTE* buff = new BYTE[len+2];
	f.Read(buff,len);
	buff[len]=0; buff[len+1] = 0;
	f.Close();

	//convert to unicode if necessary
	
	if(buff[0] == 0xFF && buff[1] == 0xFE) //unicode
	{
		TCHAR* pStart = (TCHAR*)(buff + 2);
#ifdef _UNICODE
		int l = _tcslen(pStart)+1;
		TCHAR* pRet = new TCHAR[l];
		_tcscpy(pRet,pStart);
		pRet[l-1] = 0;
		delete[] buff;
		return pRet;		
#else
		char* mbcs = CI18N::Unicode2MBCS((wchar_t*)pStart);
		delete[] buff;
		return mbcs;
#endif
	}
	else	//ANSI
	{
#ifdef _UNICODE	
		wchar_t* unicode= CI18N::MBCS2Unicode((char*)buff);
		delete[] buff;
		return unicode;
#else
		return (TCHAR*)buff;
#endif
	}
}

BOOL CDiskIO::FileWriteBuffer(LPCTSTR lpszFilename,LPCTSTR lpszTextBuffer)
{
	CFile f;
	if(f.Open(lpszFilename, 
		CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite|CFile::shareDenyNone))
	{
		return FALSE;
	}
	f.SeekToBegin();
	f.Write((void*)(LPCTSTR)lpszTextBuffer, _tcslen(lpszTextBuffer)*sizeof(TCHAR));
	f.Close();
	return TRUE;
}

BOOL CDiskIO::FileDelete(LPCTSTR lpszFilePath)
{
	try
	{
		CFile::Remove(lpszFilePath);
	}
	catch(...)
	{
	
	}
	return (!PathExists(lpszFilePath));
}

BOOL CDiskIO::FileRename(LPCTSTR lpszOldName,LPCTSTR lpszNewName)
{
	CFile::Rename(lpszOldName,lpszNewName);
	return (!PathExists(lpszNewName));
}


BOOL CDiskIO::DirCreate(LPCTSTR lpszDirPath)
{
	return (SHCreateDirectoryEx(NULL,lpszDirPath,NULL) 
		== ERROR_SUCCESS);
}